package com.example.a2207_zh.net

import com.blankj.utilcode.util.SPUtils
import com.example.a2207_zh.utils.ConsUtils
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

//封装网络请求框架
class RetrofitUtils {
    companion object{
        fun getRetrofit():Retrofit{
            val okHttpClient = OkHttpClient.Builder()
                .readTimeout(5,TimeUnit.SECONDS)
                .writeTimeout(5,TimeUnit.SECONDS)
                .connectTimeout(5,TimeUnit.SECONDS)
                .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                //自定义拦截器
                .addInterceptor {
                    //从Sp中获取登录成功保存的token 或者sn-token
                    val token = SPUtils.getInstance().getString("token")
                    //把token作为请求头添加到请求路径中
                    val request = it.request().newBuilder().addHeader("token",token).build()
                    it.proceed(request)
                }
                .build()
            val retrofit = Retrofit.Builder()
                .baseUrl(ConsUtils.BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
            return retrofit
        }
    }
}